package com.woniu.shiro_config;

import com.woniu.filters.JWTFilter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Rain
 * @Description :shiro配置类
 * @date 2022/09/06 14:20
 */
@Configuration
public class ShiroConfig {

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(MyJWTRealm myJWTRealm){
        //配置安全管理器,传入自定义域
        return new DefaultWebSecurityManager(myJWTRealm);
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        //创建shiro过滤器工厂
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        factoryBean.setSecurityManager(defaultWebSecurityManager);

        //设置自定义jwt过滤器
        Map<String, Filter> filters = new HashMap<>();
        filters.put("jwt",new JWTFilter());
        factoryBean.setFilters(filters);

        //配置URL拦截需求
        Map<String ,String > filterChainDefinitionMap = new HashMap<>();
        //所有URL通过jwt过滤器
        filterChainDefinitionMap.put("/**", "jwt");
        //login和401通过默认过滤器
        filterChainDefinitionMap.put("/login","anon");
        filterChainDefinitionMap.put("/401","anon");
        factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return factoryBean;
    }
}
